<template>
    <div>
         <!-- 面包屑导航区 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>权限管理</el-breadcrumb-item>
        <el-breadcrumb-item>菜单列表</el-breadcrumb-item>
        </el-breadcrumb>
         <!-- 卡片视图 -->
         <el-card>
            <!-- 搜索 添加 -->
            <el-row :gutter="20">
                <el-col :span="10">
                    <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getRightsList">
                        <el-button type="success" slot="append" icon="el-icon-search" @click="getRightsList"></el-button>
                    </el-input>
                </el-col>
<!--                <el-col :span="3">-->
<!--                    <el-button type="success">批量导出</el-button>-->
<!--                </el-col>-->
<!--                <el-col :span="3">-->
<!--                    <el-button type="danger">批量删除</el-button>-->
<!--                </el-col>-->
                </el-col :span="4">
                    <el-button type="primary" style="float: right;margin-right: 40px;" @click="showAddMenuDialog">添加菜单</el-button>
                </el-col>
            </el-row>
             <el-table 
                ref="rightsTable"
                v-loading="loading"
                element-loading-text="拼命加载中"
                element-loading-spinner="el-icon-loading"
                element-loading-background="rgba(0, 0, 0, 0.8)"
                :data="rightsList" 
                @selection-change="handleSelectionChange"
                header-row-class-name="table_header" 
                :header-cell-style="table_header" 
                :row-key="getRowKeys"
                border 
                stripe
                >
                 <el-table-column type="selection" :reserve-selection="true"></el-table-column>
                 <el-table-column type="index" label="序号" width="100px" align="center"></el-table-column>
                 <el-table-column label="权限名称" prop="name" align="center"></el-table-column>
                 <el-table-column label="权限路径" prop="path" align="center"></el-table-column>
                 <el-table-column label="权限等级" prop="level" align="center">
                     <template slot-scope="scope">
                        <el-tag v-if="scope.row.level === 0">一级</el-tag>
                        <el-tag type="success" v-else-if="scope.row.level === 1">二级</el-tag>
                        <el-tag type="danger" v-else>三级</el-tag>
                     </template>
                 </el-table-column>
                 <el-table-column label="操作" align="center" min-width="80px">
                    <template slot-scope="scope">
                        <el-tooltip
                        class="item"
                        effect="dark"
                        content="编辑菜单"
                        :enterable="false"
                        placement="top"
                        >
                            <el-button
                            type="primary"
                            icon="el-icon-edit"
                            size="mini"
                            circle
                            @click="showEditMenuDialog(scope.row)"
                            ></el-button>
                        </el-tooltip>
                        <el-tooltip
                        class="item"
                        effect="dark"
                        content="删除菜单"
                        :enterable="false"
                        placement="top"
                        >
                            <el-button
                            type="danger"
                            icon="el-icon-delete"
                            size="mini"
                            circle
                            @click="removeMenuById(scope.row.ID, scope.row.name)"
                            ></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
             </el-table>
              <!-- 分页区域 -->
            <div class="pager-box">
                <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="queryInfo.pageNum"
                    :page-sizes="[2, 5, 10, 15]"
                    :page-size="queryInfo.pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    prev-text="上一页"
                    next-text="下一页"
                    :total="total"
                    background
                    hide-on-single-page
                ></el-pagination>
            </div>
         </el-card>
          <!-- 添加菜单的对话框 -->
         <el-dialog 
            title="添加菜单" 
            :visible.sync="addMenuDialogVisible" 
            width="50%" 
            @close="MenuDialogClosed('addMenuFormRef')"
            >
            <el-form
                :model="MenuForm"
                :rules="MenuFormRules"
                ref="addMenuFormRef"
                label-width="100px"
            >
                <el-form-item label="菜单名称：" prop="name">
                    <el-input v-model="MenuForm.name"></el-input>
                </el-form-item>
                 <el-form-item label="父级菜单：">
                    <!-- options：数据源 -->
                    <!-- props：指定配置对象 -->
                    <el-cascader
                        v-model="selectedKeys"
                        :options="parentMenuList"
                        :props="cascaderProps"
                        @change="parentMenuChanged"
                        clearable
                        filterable
                        style="width: 100%"
                    >
                    </el-cascader>
                </el-form-item>
                <el-form-item label="菜单路径：" prop="path">
                    <el-input v-model="MenuForm.path"></el-input>
                </el-form-item>
                <el-form-item label="菜单排序：" prop="sort">
                    <el-input type="number" onkeyup="value=value.replace(/[^\d]/g,'')" v-model.number="MenuForm.sort"></el-input>
                </el-form-item>
                <el-form-item label="菜单图标：" prop="icon">
                    <el-input v-model="MenuForm.icon"></el-input>
                </el-form-item>
                <el-alert
                   title="注意：一级菜单排序不能重复"
                    type="warning">
                </el-alert>
               
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addMenuDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addMenu">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 编辑菜单的对话框 -->
         <el-dialog 
         :close-on-click-modal="false"
         title="编辑菜单" :visible.sync="editMenuDialogVisible" width="50%" @close="MenuDialogClosed('editMenuFormRef')">
            <el-form
                :model="MenuForm"
                :rules="MenuFormRules"
                ref="editMenuFormRef"
                label-width="100px"
            >
                <el-form-item label="菜单名称：" prop="name">
                    <el-input v-model="MenuForm.name"></el-input>
                </el-form-item>
                 <el-form-item label="父级菜单：">
                    <el-cascader
                        v-model="selectedKeys"
                        :options="parentMenuList"
                        :props="cascaderProps"
                        @change="parentMenuChanged"
                        clearable
                        filterable
                        style="width: 100%"
                        placeholder="一级菜单，无父级"
                    >
                    </el-cascader>
                </el-form-item>
                <el-form-item label="菜单路径：" prop="path">
                    <el-input v-model="MenuForm.path"></el-input>
                </el-form-item>
                <el-form-item label="菜单排序：" prop="sort">
                    <el-input type="number" v-model.number="MenuForm.sort"></el-input>
                </el-form-item>
                <el-form-item label="菜单图标：" prop="icon">
                    <el-input v-model="MenuForm.icon"></el-input>
                </el-form-item>
                <el-alert
                   title="注意：一级菜单排序不能重复"
                    type="warning">
                </el-alert>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editMenuDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editMenu">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
    data () {
        var validateSort = (rule, value, callback) => {
            if (this.MenuForm.parent_id === 0 && this.sortList.indexOf(value) > -1 && this.addMenuDialogVisible) {
                callback(new Error("一级菜单排序不能重复"));
            } else {
                callback();
            }
        };
        return {
        // 权限列表
            queryInfo: {
                query: '',
                // 当前页数
                pageNum: 1,
                // 每页显示多少数据
                pageSize: 10,
            },
            rightsList: [],
            parentMenuList: [],
            total: 0,
            loading: true,
            multipleSelection: [],
            value: '',
            addMenuDialogVisible: false,
            editMenuDialogVisible: false,
            selectedKeys: [],
            MenuForm: {},
            MenuFormRules: {
                name: [
                    { required: true, message: '请输入菜单名称', trigger: 'blur' }
                ],
                sort: [
                    { validator: validateSort, trigger: "blur" }
                ],
                icon: [
                    { required: true, message: '请输入菜单图标', trigger: 'blur' }
                ]
            },
            // 指定级联选择器的配置对象
            cascaderProps: {
                // 配置触发选项 hover/click
                expandTrigger: 'hover',
                value: 'ID',
                label: 'name',
                children: 'children',
                checkStrictly: true,
            },
        }
    },
    created () {
        this.getRightsList();
        this.getParentMenuList();
    },
    methods: {
        getRowKeys(row){//翻页也保存勾选状态
            return row.ID;
        },
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },

        table_header(row, column, rowIndex, columnIndex){
            return 'background-color: #409EFF; color: white'
        },
          // 监听 pagesize改变的事件
        handleSizeChange (newSize) {
            // console.log(newSize)
            this.queryInfo.pageSize = newSize
            this.getRightsList()
        },
        // 监听 页码值 改变事件
        handleCurrentChange (newSize) {
            // console.log(newSize)
            this.queryInfo.pageNum = newSize
            this.getRightsList()
        },
        async getRightsList () {
            var v1 = this;
            const { data: res, status: status } = await this.axios.get('menus/getMenuList', {params: v1.queryInfo})
            if (status !== 200) {
                return this.$message.error('获取权限列表失败！')
            }
            this.rightsList = res.data.menus
            this.total = res.data.total
            this.loading = false
        },
         // 添加操作
        showAddMenuDialog () {
            // 再打开对话框
            this.addMenuDialogVisible = true
        },
        // 获取父级分类的数据
        async getParentMenuList () {
            const { data: res, status: status } = await this.axios.get('menus/getAllMenuTree', {
                params: { type: 2 }
            });
            if (status !== 200) {
                return this.$message.error('获取父级分类失败！')
            }
            this.parentMenuList = res.data.menus;
            this.sortList = res.data.sort_list;
        },
        // 添加分类 选择项发生变化触发
        parentMenuChanged () {
            // 如何selectKeys 数组的长度>0 说明选中父级分类
            if (this.selectedKeys.length > 0) {
                // 父级分类的Id
                this.MenuForm.parent_id = this.selectedKeys[this.selectedKeys.length - 1]
                // 当前分类的等级
                this.MenuForm.level = this.selectedKeys.length
            } else {
                // 父级分类的Id
                this.MenuForm.parent_id = 0
                // 当前分类的等级
                this.MenuForm.level = 0
            }
        },
        // 添加分类
        addMenu () {
            this.$refs.addMenuFormRef.validate(async valid => {
                if (!valid) return
                const { data: res, status: status } = await this.axios.post('menus/addMenu', this.MenuForm)
                if (status !== 200) {
                    return this.$message.error('添加分类失败！')
                }
                this.$message.success('添加分类成功！')
                this.getRightsList()
                this.addMenuDialogVisible = false
            })
        },
        // 添加分类 重置表单
        MenuDialogClosed (formName) {
            this.selectedKeys = [];
            this.MenuForm = {};
            this.$refs[formName].resetFields();
        },
         // 显示编辑对话框
        async showEditMenuDialog (menu) {
            console.log(menu)
            if (menu.level === 2) {
                const { data: res, status: status } = await this.axios.get('menus/getParentIds', {params:{"parent_id": menu.parent_id}})
                if (status !== 200) return this.$message.error('获取菜单父ID失败！')
                this.selectedKeys = res.data
            }else{
                this.selectedKeys = [menu.parent_id]
            }
            this.MenuForm = menu;
            this.editMenuDialogVisible = true
        },
        // 编辑菜单
        editMenu () {
            this.$refs.editMenuFormRef.validate(async valid => {
                if (!valid) return;
                const { data: res, status: status } = await this.axios.put('menus/updateMenu', this.MenuForm)
                if (status !== 200) return this.$message.error('更新菜单失败！');
                this.$message.success('更新菜单成功！');
                this.getRightsList();
                this.editMenuDialogVisible = false
            })
        },
        // 删除菜单
        async removeMenuById(id, name) {
            const confirmResult = await this.$confirm('此操作将永久删除菜单 ' + name + ', 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(err => err);
            if (confirmResult !== 'confirm') { return this.$message.info('已取消删除！') }
            const { data: res, status: status } = await this.axios.delete('menus/deleteMenu', {params: {"id": id}})
            if (status !== 200) { return this.$message.error('删除菜单失败！') }
            this.$message.success('删除菜单成功！');
            this.getRightsList()
        },
    },
}
</script>
<style lang="less" scoped>
</style>